package unionfindset;

import java.util.Arrays;

public class UnionFindSet {
    public int[] elem;
    public int usedSize;

    public UnionFindSet(int n) {
        this.elem = new int[n];
        Arrays.fill(elem, -1);
    }

    /**
     * 查找数据x的根节点
     * @param x
     * @return
     */
    public int findRoot(int x) {
        if(x < 0) {
            throw new IndexOutOfBoundsException("下标不合法, 是负数");
        }
        while (elem[x] >= 0) {
            x = elem[x];
        }
        return x;
    }

    /**
     * 查询x1和x2是不是同一个集合
     * @param x1
     * @param x2
     * @return
     */
    public boolean isSameUnionFindSet(int x1, int x2) {
        int index1 = findRoot(x1);
        int index2 = findRoot(x2);
        if(index1 == index2) {
            return true;
        }
        return false;
    }

    /**
     * 合并操作
     * @param x1
     * @param x2
     */
    public void union(int x1, int x2) {
        int index1 = findRoot(x1);
        int index2 = findRoot(x2);
        if(index1 == index2) {
            return;
        }
        elem[index1] = elem[index1] + elem[index2];
        elem[index2] = index1;
    }

    public int getCount() {
        int count = 1;
        for(int x : elem) {
            if(x < 0) {
                count++;
            }
        }
        return count;
    }

    public void print() {
        for(int i = 0; i<elem.length; i++) {
            System.out.printf("%3d", i);
        }
        System.out.println();
        for(int x : elem) {
            System.out.printf("%3d", x);
        }
        System.out.println();
        System.out.println();
    }

    public static void main(String[] args) {
        UnionFindSet unionFindSet = new UnionFindSet(10);
        unionFindSet.union(0, 6);
        unionFindSet.union(0, 7);
        unionFindSet.union(0, 8);

        unionFindSet.print();

        unionFindSet.union(1, 4);
        unionFindSet.union(1, 9);

        unionFindSet.print();

        unionFindSet.union(2, 3);
        unionFindSet.union(2, 5);

        unionFindSet.print();

        unionFindSet.union(8, 1);
        unionFindSet.print();

        System.out.println(unionFindSet.isSameUnionFindSet(6, 9));
    }
}
